#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      shoo
#
# Created:     13/06/2011
# Copyright:   (c) shoo 2011
# Licence:     <your licence>
#-------------------------------------------------------------------------------
import ver
import logging
import mail_addr
import re
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util

logging.getLogger().setLevel(logging.DEBUG)

HTML=u"""
<html>
<head><title>メールアドレスインポート</title></head>
<body>
<div>%s</div>
<div style="padding:10px; margin:30px; width:300px; font-weight:bold; font-size:large; border:1px solid #555">
メールアドレス1,名前1<br>
メールアドレス2,名前2<br>
</div>
<div>
という形式で入力してください。<br>
例) hogehoge@example.jp,テスト太郎<br>
</body>
<form method="POST">
<input type="submit" value="更新"><br>
<textarea name="csv" rows="20" cols="70">
%s
</textarea>
</form>
</html>
"""

# cronで起動されるメールチェックリクエストハンドラー
class AddrImportHandler(webapp.RequestHandler):
    def get(self):
        html = HTML % (ver.VER, mail_addr.get_all_csv())
        self.response.out.write(html)

    def post(self):
        data = self.request.get("csv")
        addrs=[]
        for line in re.split(r'\r?\n', data):
            vals = re.split(r'\s*,\s*',line,2)
            if len(vals)!=2:
                continue
            addrs.append((trim(vals[0]), trim(vals[1])))

        del_and_insert(addrs)
        self.response.out.write("""
<html>
<head>
<meta http-equiv="refresh" content="3;URL=./">
</head>
<body>
OK
</body>
</html>
        """)

def trim(s):
    s = re.sub(r'^"',"",s)
    return re.sub(r'"$',"",s)

def del_and_insert(addrs):
    mail_addr.delete_all()
    for i, ary in enumerate(addrs):
        mail_addr.MailAddr(key_name=ary[0], num=i+1, display_name=ary[1]).put()

def main():
    application = webapp.WSGIApplication([('/', AddrImportHandler)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
